package com.biye.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.base.common.edu.entity.SysGroup;
import com.base.common.edu.entity.SysRole;
import com.base.common.edu.mapper.GroupMapper;
import com.base.common.edu.mapper.RoleMapper;
import com.base.common.httpStatusCode.enumDefine.StatusCode;
import com.biye.api.service.AuthorityService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AuthorityServiceImpl implements AuthorityService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private GroupMapper groupMapper;

    @Override
    public JSONObject queryAllRoleOrGroupAuthorityList() {
        JSONObject jsonObject = new JSONObject();
        String msg = "暂无数据";
        int statusCode = StatusCode.Failure._statusCode;
        // 查询角色
        List<SysRole> roleMaps = roleMapper.queryAllRoles();
        List<String> roleArray = new ArrayList<>();
        if ( roleMaps.size() > 0 ) {
            String power_name;
            // 为了适应Element-UI的checkbox多选框，重新组装返回数据
            for ( SysRole role : roleMaps ) {
                power_name = (String) role.getRoleName();
                roleArray.add(power_name);
            }
        }
        jsonObject.put("roles", roleArray);
        // 查询组
        List<SysGroup> groups = groupMapper.queryAllGroups();
        List<String> groupArray = new ArrayList<>();
        if ( groups.size() > 0 ){
            String group_name;
            for(SysGroup g : groups) {
                group_name = g.getGroupName();
                groupArray.add(group_name);
            }
        }
        jsonObject.put("groups", groupArray);
        // 判断数据修改响应信息
        int countSize = roleMaps.size() + groups.size();
        if ( countSize > 0 ){
            msg = "查询成功";
            statusCode = StatusCode.Success._statusCode;
        }
        jsonObject.put("msg", msg);
        jsonObject.put("statusCode", statusCode);
        return jsonObject;
    }

    @Override
    public JSONObject queryAllRoleOrGroupAuthorityListByStaffId(Map<String, Object> request) {
        JSONObject jsonObject = new JSONObject();
        String msg = "暂无数据";
        int statusCode = StatusCode.Failure._statusCode;
        // 检查请求参数
        if ( !request.containsKey("userId") || !request.containsKey("userType") ){
            jsonObject.put("msg", "请求参数不正确");
            jsonObject.put("statusCode", statusCode);
            return jsonObject;
        }
        // 获取请求参数
        String user_id = (String) request.get("userId");
        String user_type = (String) request.get("userType");
        user_type = "".equals(user_type) ? null : user_type;
        if (user_type == null || !"tea".equals(user_type)){
            jsonObject.put("msg", "不支持对该类用户进行权限修改");
            jsonObject.put("statusCode", statusCode);
            return jsonObject;
        }
        // 该用户拥有的权限：先查询角色
        List<SysRole> sysRoles = roleMapper.queryRolesByStaffId(user_id);
        List<String> roleArray = new ArrayList<>();
        if ( sysRoles.size() > 0 ) {
            String power_name;
            // 为了适应Element-UI的checkbox多选框，重新组装返回数据
            for ( SysRole role : sysRoles ) {
                power_name = (String) role.getRoleName();
                roleArray.add(power_name);
            }
        }
        jsonObject.put("roles", roleArray);
        // 该用户拥有的权限：再查询角色组
        List<SysGroup> sysGroups = groupMapper.queryGroupsByStaffId(user_id);
        List<String> groupArray = new ArrayList<>();
        if ( sysGroups.size() > 0 ){
            String group_name;
            for(SysGroup g : sysGroups) {
                group_name = g.getGroupName();
                groupArray.add(group_name);
            }
        }
        jsonObject.put("groups", groupArray);
        // 判断数据修改响应信息
        int countSize = sysRoles.size() + sysGroups.size();
        if ( countSize > 0 ){
            msg = "查询成功";
            statusCode = StatusCode.Success._statusCode;
        }
        jsonObject.put("msg", msg);
        jsonObject.put("statusCode", statusCode);
        return jsonObject;
    }

    @Override
    public JSONObject updateStaffAuthorityList(Map<String, Object> requestMap) {
        JSONObject jsonObject = new JSONObject();
        String msg = "操作成功，未变化";
        int statusCode = StatusCode.Failure._statusCode;
        // 请求参数校验
        if ( !requestMap.containsKey("userId") || !requestMap.containsKey("userType") || !requestMap.containsKey("newGroup") || !requestMap.containsKey("newRoles") ){
            jsonObject.put("msg", "请求参数不正确");
            jsonObject.put("statusCode", statusCode);
            return jsonObject;
        }
        // 获取请求参数
        String user__id = (String) requestMap.get("userId");
        String user_type = (String) requestMap.get("userType");
        user_type = "".equals(user_type) ? null : user_type;
        if (user_type == null || !"tea".equals(user_type)){
            jsonObject.put("msg", "不支持对该类用户进行权限修改");
            jsonObject.put("statusCode", statusCode);
            return jsonObject;
        }
        List<String> group_list = (List<String>) requestMap.get("newGroup");
        List<String> role_list = (List<String>) requestMap.get("newRoles");
        // TODO
        // 一、首先根据用户id查询用户原来的权限
        List<SysRole> user_role_list = roleMapper.queryRolesByStaffId(user__id);
        List<SysGroup> user_group_list = groupMapper.queryGroupsByStaffId(user__id);
        /*
        新增一个变量用于记录新增和移除的记录数
         */
        int changeExcessCount = 0;  // 权限新增的
        int changeAbsentCount = 0;  // 权限移除的
        // 二、比较操作中新增的权限，并更新 []
        // 2-1比较组的差集（新增）
        List<String> excess_group = new ArrayList<>();
        boolean g_flag1 = false;
        for ( String updGroup : group_list ) {
            // 判断我的组用户中有没有的
            g_flag1 = false;
            for ( SysGroup g : user_group_list ){
                if ( updGroup.equals(g.getGroupName()) ){
                    g_flag1 = true;
                    break;  // 跳出该层for
                }
            }
            if ( !g_flag1 ){
                changeExcessCount += 1;
                excess_group.add(updGroup);
            }
        }
        // 2-2比较角色的差集（新增）
        List<String> excess_role = new ArrayList<>();
        boolean r_flag1 = false;
        for ( String updRole : role_list ) {
            // 判断用户Role中有没有该角色
            r_flag1 = false;
            for ( SysRole r : user_role_list ) {
                if ( updRole.equals(r.getRoleName()) ) {
                    r_flag1 = true;
                    break;  // 跳出该层for
                }
            }
            if ( !r_flag1 ){
                changeExcessCount += 1;
                excess_role.add(updRole);
            }
        }
        if ( changeExcessCount > 0 ){
            // 2-3 对于新增的权限进行持久化操作
            // 2-3组：持久化
            String tmp_g_id1;
            for ( String gName : excess_group ) {
                tmp_g_id1 = groupMapper.switchGroupNameToId(gName);
                groupMapper.saveTieToStaffAndGroup(tmp_g_id1, user__id);
            }
            // 2-3角色：持久化
            String tmp_r_id1;
            for ( String rName : excess_role ) {
                tmp_r_id1 = roleMapper.switchRoleNameToId(rName);
                roleMapper.saveTieToRoleStaff(tmp_r_id1, user__id);
            }
        }
        // 三、比较操作中移除的权限，并更新 [由于操作中使用的都是组名或者]
        // 3-1组：直接操作
        String g_temp_name;
        for ( SysGroup gg : user_group_list ){
            g_temp_name = gg.getGroupName();
            if ( !group_list.contains(g_temp_name) ){
                groupMapper.removeTieToStaffAndGroup(gg.getGroupId(), user__id);
                changeAbsentCount += 1;
            }
        }
        // 3-2角色：直接操作
        String r_temp_name;
        for ( SysRole rr : user_role_list ){
            r_temp_name = rr.getRoleName();
            if ( !role_list.contains(r_temp_name) ){
                roleMapper.removeTieToRoleStaff(rr.getRoleId(), user__id);
                changeAbsentCount += 1;
            }
        }
        if ( changeExcessCount + changeAbsentCount > 0 ){
            statusCode = StatusCode.Success._statusCode;
            msg = "操作成功，已更新";
        }
        jsonObject.put("msg", msg);
        jsonObject.put("statusCode", statusCode);
        return jsonObject;
    }

}
